#!/bin/bash

APP_NAME='app.jar'

#检查程序是否在运行
is_exist(){
	pid=`jps -l | grep $APP_NAME | grep -v grep | awk '{print $1}'`
	#如果不存在返回1，存在返回0     
	if [ -z "${pid}" ]; then
		return 1
	else
		return 0
	fi
}

#运行状态
status(){
	is_exist
	if [ $? -eq 0 ]; then
		echo "$(date +%F%T) === ${APP_NAME} is already running. pid=${pid}" >>/opt/app/run.log
		stop
	fi
	start
}

#启动方法
start(){
  rm -rf run.log
  echo "$(date +%F%T) === start ===" >>/opt/app/run.log
  nohup /opt/jdk-17.0.10/bin/java -jar $APP_NAME >>/opt/app/run.log 2>&1 &
  echo "..."
  sleep 5
  is_exist
  if [ $? -eq 0 ]; then
    echo "$(date +%F%T) === ${APP_NAME} is running success. pid=${pid}" >>/opt/app/run.log
  fi
}

#停止方法
stop(){
  echo "$(date +%F%T) === start stopping process pid=${pid}" >>/opt/app/run.log
  kill -15 $pid
  echo "..."
  sleep 2
  is_exist
  if [ $? -eq 0 ]; then
    echo "$(date +%F%T) === ${APP_NAME} still in the running. pid=${pid}" >>/opt/app/run.log
  else
    echo "$(date +%F%T) === ${APP_NAME} has stopped running." >>/opt/app/run.log
  fi
}

status
